package com.luo.gmall.order.interceptor;

import com.luo.gmall.order.entity.UserInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Zoro
 * @date 2021年11月22
 * 拦截器获取登录信息
 */
@Component

public class LoginInterceptor implements HandlerInterceptor {


    private static final ThreadLocal<UserInfo> USER_INFO = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String userId = request.getHeader("userId");
        String username = request.getHeader("username");
        UserInfo userInfo = new UserInfo(Long.valueOf(userId), null, username);
        USER_INFO.set(userInfo);
        return true;
    }

    public static UserInfo getUserInfo() {
        // 从ThreadLocal中获取userInfo
        return USER_INFO.get();
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("handler方法执行后，页面渲染前。。。。。。");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在页面渲染前将ThreadLocal中用完的数据清除（请求结束，线程没有结束）
        USER_INFO.remove();
        System.out.println("页面渲染后。。。。。");
    }
}
